package digital.store.springmvc.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;





import org.springframework.stereotype.Repository;

import digital.store.springmvc.dao.ProductDao;
import digital.store.tutorial.springmvc.model.Product;
/**
 * Implement a normal JPA DAO
 * @author vinh
 *
 */
@Repository
public class ProductDaoImpl implements ProductDao {
    @PersistenceContext
    private EntityManager em;
    
  
    
    public void saveOrUpdate(Product product) {
        if (product.getId() != null) {
            em.merge(product);
        } else {
            em.persist(product);
        }
    }
    
    public void delete(Long id) {
        Product product = findById(id);
        em.remove(product);
    }
    
    @SuppressWarnings("unchecked")
    public List<Product> findAll() {
        return em.createQuery("SELECT p FROM Product p").getResultList();
    }
    
    public Product findById(Long id) {
        return em.find(Product.class, id);
    }
    
    public List<Product> findByCategoryId(Long id){
    	 return em.createQuery("SELECT p FROM Product p WHERE p.category.id = '" + id + "'",Product.class).getResultList();
    }
    
}
